package com.justexample.java.util.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.Scanner;
import javax.swing.*;
import java.lang.*;

public class CompressZip {

    public static void main(String[] args) throws Exception{
		Scanner Synchronize = new Scanner(System.in);
		System.out.println("Please Enter the location of the folder :");
        String sourceFolderName =  Synchronize.nextLine();//user needs to input folder path (e.g c:\windows)
        String prompt1 = "Please Enter the name of the output :"; //user needs to input output name and the file type (e.g CompressedWindows.zip)
      System.out.println("Ex: c:'\'FileNameOutput.zip");
        String outputFileName = Synchronize.nextLine();
        JOptionPane.showMessageDialog(null, prompt1, "My Program", JOptionPane.INFORMATION_MESSAGE);

        FileOutputStream fos = new FileOutputStream(outputFileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        zos.setLevel(9);

        System.out.println("Begin to compress folder : " + sourceFolderName + " to " + outputFileName);
        addFolder(zos, sourceFolderName, sourceFolderName);

        zos.close();
        System.out.println("the compression was successful !");
    }

    private static void addFolder(ZipOutputStream zos,String folderName,String baseFolderName)throws Exception{
        File f = new File(folderName);
        if(f.exists()){
            if(f.isDirectory()){
                File f2[] = f.listFiles();
                for(int i=0;i<f2.length;i++){
                    addFolder(zos,f2[i].getAbsolutePath(),baseFolderName);
                }
            }else{
                String entryName = folderName.substring(baseFolderName.length()+1,folderName.length());
                System.out.print("Adding entry " + entryName + "...");
                ZipEntry ze= new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(folderName);
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
                System.out.println("DONE ~!");

            }
        }else{
            System.out.println("Error : File or directory not found " + folderName);
        }

    }

}